"use strict"

var fs = require('fs');
var path = require('path');
var express = require('express');
var compression = require('compression');
var webpack = require('webpack');
var xlsx = require('node-xlsx');

var env = process.env.NODE_ENV || 'dev',
	debug = env === 'production' ? false : true;
	debug = true;
var config = require('./webpack.config.' + (debug ? 'dev' : 'prod'));

var app = express();

var port = 3000,
	host = debug ? '127.0.0.1' : '0.0.0.0';

if (debug) {
	var compiler = webpack(config);

	app.use(require('webpack-dev-middleware')(compiler, {
		noInfo: true,
		publicPath: config.output.publicPath
	}));

	app.use(require('webpack-hot-middleware')(compiler));
}

if (!debug) {
	app.use(compression());
}

app.use('/static', express.static(path.join(__dirname, 'static')));

app.get('/', function(req, res) {
	res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/timer', function(req, res) {
	var stop = new Date();

	stop.setHours(22);
	stop.setMinutes(0);
	stop.setSeconds(0);

	res.send({
		seconds: new Date().getTime(),
		time: stop.getTime() - new Date().getTime()
	})
})

app.get('/getData', function(req, res) {
	
	var query = req.query;
	/*
	if( query.data && query.data[0] ){
		
		var data = [ query.data ,[true, false, null, 'sheetjs'],['foo','bar',new Date('2014-02-19T14:30Z'), '0.3'], ['baz', null, 'qux']];
		
		var buffer = xlsx.build([{name: "mySheetName", data: data}]);
		
		fs.writeFileSync('b.xlsx', buffer, 'binary');
		
		res.send('export successfully!');
		
	}
	*/
	res.send({
		msg: '成功'
	})
})

app.get('/listimg', function(req, res) {
	var src = listimgsrc || randomimg();

	res.sendFile(src);
})

app.listen(port, function(err) {
	if (err) {
		console.log(err);
		return;
	}

	console.log('Listening at http://', host, port);
});

var dayarr = [5242, 5184, 15828, 5419, 58];

function randomimg() {
	var day = new Date().getDay();
	var dirpath = './static/img';
	var src = '';

	console.log('day ', day); 
	if (day == 0 || day == 6) {
		src = path.join(dirpath, '38.jpg');
	} else {
		var cat = dayarr[day - 1];
		var dir = path.resolve(dirpath, cat + '');

		var list = fs.readdirSync(dir);
		var length = list.length;
		var num = Math.floor(Math.random() * length);

		console.log(src = path.join(dir, list[num]));
	}

	return src;

}

const listimgsrc = randomimg();
